package com.zh.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zh.service.SmsService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {
    @Override
    public boolean sendSms(String phoneNum, String templateCode, Map<String, Object> code) {
        // 连接阿里云，accessKeyId： 自己的签名，accessSecret，密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GCNumm6HFLt1EVGw4fB", "QNduODwVPBgZ4s3CQ0j5D7SZiWEVd3");
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求！
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);

        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //自定义参数（手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", phoneNum); // 要发送的手机号
        request.putQueryParameter("SignName", "ABC商城");   // 签名名称
        request.putQueryParameter("TemplateCode", templateCode); // 模板编码
        // 构建一个短信的验证码
        request.putQueryParameter("TemplateParam", JSON.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
